﻿using AutoMapper;
using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.Z.BasicData.API.Write.Application.Role
{
    public class RoleAddCommandHandler : IRequestHandler<RoleAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_Role> roleRepository;
        private readonly IMapper mapper;

        public RoleAddCommandHandler(IBaseRepository<T_Role> roleRepository, IMapper mapper)
        {
            this.roleRepository = roleRepository;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(RoleAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "添加成功";
            var roles = roleRepository.GetAll().Where(p => p.RoleName == request.RoleName);
            if (roles.Count() > 0)
            {
                result.Code = APIEnum.faile;
                result.Message = "角色名称已存在";
                return await Task.FromResult(result);
            }
            var role = mapper.Map<T_Role>(request);
            result.Data = await roleRepository.Add(role);
            return await Task.FromResult(result);

        }
    }
}
